package main

import (
	"context"
	"fmt"
	"time"

	"go.etcd.io/etcd/clientv3"
)

func main() {
	config := clientv3.Config{
		Endpoints:   []string{"localhost:2379"},
		DialTimeout: 5 * time.Second,
	}

	client, err := clientv3.New(config)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer client.Close()

	lease := clientv3.NewLease(client)                      // 创建一个租约
	leaseResp, err := lease.Grant(context.Background(), 10) // 设置租约超时 10秒
	if err != nil {
		fmt.Println(err)
		return
	}
	leaseRespChan, _ := lease.KeepAlive(context.Background(), leaseResp.ID) // 通过keeplive定期发送心跳

	kv := clientv3.NewKV(client)
	key := "demo.rpc"
	value := "127.0.0.1:9000"
	fmt.Println("key", key)

	// 绑定带有心跳的租约并将自身服务信息put到etcd中心
	_, err = kv.Put(context.Background(), key, value, clientv3.WithLease(leaseResp.ID))
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("register service success")

	for {
		select {
		case i := <-leaseRespChan:
			fmt.Println("heart beat", i.String()) // 心跳信息
		}
	}
}
